<?php

namespace App\Console\Commands;

use App\Services\GraspService;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class EverydayNewGoodCommand extends Command {
	/**
	 * The name and signature of the console command.
	 *
	 * @var string
	 */
	protected $signature = 'sell:newGood {num?}';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = '每日爬取新商品';

	protected $microtime;

	/**
	 * Create a new command instance.
	 *
	 * @return void
	 */
	public function __construct() {
		parent::__construct();
		$this->microtime = GraspService::microtime();
	}

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 */
	public function handle() {

		$num = $this->argument('num');
		$num = $num ? $num : 1;
		$url = "http://search.kongfz.com/product_result/?status=1&pagenum=" . $num . "&price=100.00&order=9&ajaxdata=4&type=1&_=" . $this->microtime;
		print "开始抓取商品\n";
		$this->exec($url);
		print "抓取商品成功\n";
	}

	protected function exec($url) {
		$parts = parse_url($url);
		parse_str($parts['query'], $query);
		$today = Carbon::yesterday();
		$data = GraspService::exeCurl($url);
		if ($data == false) {
			Log::error("没有商品，抓取失败!");
			return false;
		} else {
			$data = json_decode($data, true);
			if (!$data['data']['itemList']) {
				return [];
			}
			$itemList = $data['data']['itemList'];
			$other = $data['other'];
			$total = $other['total']; //总数
			$page_count = $other['page_count']; //总页数
			$curpage = $other['curpage']; //当前页
			GraspService::addGood($itemList, $today);
			if ($curpage >= $page_count) {
				return false;
			}
			$next_number = $query['pagenum'] + 1;
			$next_url = "http://search.kongfz.com/product_result/?status=1&pagenum=" . $next_number . "&price=100.00&order=9&ajaxdata=4&type=1&_=" . $this->microtime;
			print "正在抓取第" . $next_number . "页\n";
			return $this->exec($next_url);
		}
	}
}
